package com.chezhujie.www.controller;

import com.chezhujie.www.constant.AesConstant;
import com.chezhujie.www.constant.PageInfo;
import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.domain.*;
import com.chezhujie.www.domain.vo.ActDetailAndFest;
import com.chezhujie.www.domain.vo.ActDetailAndFestAndUserVO;
import com.chezhujie.www.enums.OrderStatus;
import com.chezhujie.www.enums.RefundStatus;
import com.chezhujie.www.service.*;
import com.chezhujie.www.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.persistence.criteria.Order;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/activity")
public class CzjactivityController extends BaseController {
	private static final Logger log = LoggerFactory
			.getLogger(CzjactivityController.class);

	public CzjactivityController() {
	}

	/***
	 * 
	 * 方法名：insertCzjactivity
	 * ////////////////////////////此方法已经不用//////////////////////////////////
	 * 创建人：RUI 时间：2017年6月5日-上午9:40:38
	 * 
	 * @param businessId
	 *            商家ID
	 * @param userinfoId
	 *            用户ID
	 * @param totalAmount
	 *            总价格
	 * @param festivalActId
	 *            活动ID
	 * @param nun
	 *            购买数量
	 * @param festAmount
	 *            原价
	 * @param buyingPrice
	 *            购买价格
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("insert")
	public void insertCzjactivity(String businessId,
			@RequestParam(required = true) Integer userinfoId,
			@RequestParam(required = true) BigDecimal totalAmount,
			@RequestParam(required = true) String festivalActId,
			@RequestParam(required = true) Integer nun, BigDecimal festAmount,
			@RequestParam(required = true) BigDecimal buyingPrice,
			HttpServletRequest request, HttpServletResponse response) {

		try {
			Czjactivity czjactivity = new Czjactivity();
			if (StringUtils.isNotBlank(businessId)) {
				czjactivity.setBusinessId(businessId);
			}
			czjactivity.setActivityNum(OrderNumUtils.getOrderNo(1));
			czjactivity.setUserinfoId(userinfoId);
			czjactivity.setTotalAmount(totalAmount); // 总价格
			int i = totalAmount.compareTo(BigDecimal.ZERO);
			if (i <= 0) {
				czjactivity.setFree(0);
			}
			czjactivity.setStatus(4);
			czjactivity.setDel(1);
			czjactivity.setCreatetime(new Date());
			czjactivity.setHide(1);

			czjactivityService.insertActivity(czjactivity);

			Czjactdetail czjactdetail = new Czjactdetail();
			czjactdetail.setActivityNum(czjactivity.getActivityNum());
			czjactdetail.setFestivalActId(festivalActId);
			czjactdetail.setBuyingPrice(buyingPrice);// 购买价格
			czjactdetail.setNun(nun);
			if (null != festAmount) {
				czjactdetail.setFestAmount(festAmount);
			}
			czjactdetail.setCreatetime(new Date());

			czjactdetailService.insertCzjactdetail(czjactdetail);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userinfoId);
			map.put("totalAmount", totalAmount);
			map.put("activityId", czjactivity.getActivityId());
			map.put("activityNum", czjactivity.getActivityNum());
			jsonResult(1, "", "", map, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("err", e);
			jsonResult(0, "134", "生成订单错误", "", response);
		}
	}

	/**
	 * 
	 * 方法名：apilist 接口显示我的活动 创建人：RUI 时间：2017年6月5日-上午10:20:58
	 * 
	 * @param userinfoId
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("apilist")
	public void apilist(Integer pageNo, Integer pageSize,
			@RequestParam(required = true) Integer userinfoId,
			HttpServletRequest request, HttpServletResponse response) {

		if (null == userinfoId) {
			jsonResult(1, "148", "用户不能空", "", response);
		}
		try {

			if (null == pageNo)
				pageNo = PageInfo.DEFAULT_PAGENO;
			if (null == pageSize)
				pageSize = PageInfo.DEFAULT_PAGESIZE;
			Czjactivity czjactivity = new Czjactivity();
			czjactivity.setUserinfoId(userinfoId);
			Pagination pagination = czjactivityService.listCzjactivityApi(
					ConvertObj.toMap(czjactivity), pageNo, pageSize);
			jsonResult(1, "", "", pagination, response);

		} catch (Exception e) {
			e.printStackTrace();
			log.error("err", e);
			jsonResult(0, "135", "显示用户预定假日活动错误", "", response);
		}
	}

	/**
	 * 
	 * 
	 * 方法名：delete 删除我的订单 (修改订单状态) 创建人：RUI 时间：2017年7月10日-下午7:00:45
	 * 
	 * @param activityId
	 * @param status
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("delete")
	public void delete(@RequestParam(required = true) String activityId,
			@RequestParam(required = true) Integer status,
			HttpServletRequest request, HttpServletResponse response) {

		if (null == activityId) {
			jsonResult(1, "148", "用户不能空", "", response);
			return;
		}

		if (OrderStatus.RUNNING.getIndex() != status) {
			jsonResult(1, "161", "只能是待支付状态可删除", "", response);
			return;
		}

		try {

			Czjactivity czjactivity = new Czjactivity();
			czjactivity.setActivityId(activityId);
			czjactivity.setHide(0);
			czjactivity.setStatus(OrderStatus.UNUSE.getIndex());
			czjactivityService.updateAct(czjactivity);

			Czjactivity act = czjactivityService.queryById(activityId);
			if (null != act && null != act.getCouponsId()) {

				Czjawarduse czjawarduse = czjawarduseService.queryById(act
						.getCouponsId());
				if (OrderStatus.USE.getIndex() == czjawarduse.getStatus()) {
					czjawarduse.setStatus(OrderStatus.UNUSE.getIndex());
					czjawarduseService.updateCzjawarduse(czjawarduse);
				} else if (OrderStatus.RECEIVED.getIndex() == czjawarduse
						.getStatus()) {
					czjawarduse.setStatus(OrderStatus.UNRECEIVED.getIndex());
					czjawarduseService.updateCzjawarduse(czjawarduse);
				}
			}
			jsonResult(1, "", "", "", response);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "135", "显示用户预定假日活动错误", "", response);
		}
	}

	/***
	 * 
	 * 方法名：generateCode 生成二维码密匙 创建人：RUI 时间：2017年6月30日-下午3:09:46
	 * 
	 * @param festivalActId
	 *            订单Id
	 * @param num
	 *            数量
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("generateCode")
	public void generateCode(@RequestParam(required = true) String activityId,
			HttpServletRequest request, HttpServletResponse response) {

		try {

			/*
			 * String str=activityId+","+AesConstant.HUODONG+","+num;
			 * System.out.println(str); jsonResult(1, "", "",
			 * Base64.getBase64(str), response);
			 */

			Integer num = czjactivityService.getNum(activityId); // 总数量
			Integer useNum = czjromotionService.getSumNumByActId(activityId);// 已扫描数量
			if (null == num) {

				jsonResult(0, "170", "订单不存在，非法请求", "", response);
				return;
			}
			if (null == useNum) {
				useNum = 0;
			}
			int donum = num.intValue() - useNum.intValue();// 可以扫描的数量
			String str = activityId + "," + AesConstant.HUODONG + "," + donum+","+num;
			jsonResult(1, "", "", Base64.getBase64(str), response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("err", e);
			jsonResult(0, "151", "生成活动二维码密匙错误", "", response);
		}
	}

	/**
	 * 
	 * 
	 * 方法名：getOrderDetail 获得活动详情 创建人：RUI 时间：2017年7月6日-下午6:53:57
	 * 
	 * @param activityId
	 * @param num
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("getOrderDetail")
	public void getOrderDetail(
			@RequestParam(required = true) String activityId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {

		try {

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("activityId", activityId);
			ActDetailAndFest czjactivity = czjactivityService
					.getActDetailAndFest(map);
			if(null==czjactivity){
				jsonResult(0, "175", "查看活动订单失败", "", response);
				return ;
			}
			if(null==czjactivity.getNun()){
				czjactivity.setNun(0);
			}
			
			Integer  idenNum=czjromotionService.getSumNumByActId(activityId);//已试用数量
			if(null==idenNum){
				idenNum=0;
			}
			Map<String, Object> result=new HashMap<String, Object>();
				result.put("czjactivity", czjactivity);
				result.put("idenNum", idenNum);
			jsonResult(1, "", "", result, response);

		} catch (Exception e) {
			e.printStackTrace();
			log.error("err", e);
			jsonResult(0, "151", "获得活动详情失败", "", response);
		}
	}

	/**
	 * 
	 * 方法名：changeFestStatus 修改活动状态 创建人：RUI 时间：2017年6月30日-下午4:18:06
	 * 
	 * @param festivalActId
	 * @param activityId
	 * @param userId
	 * @param num
	 * @param type
	 *            = 'CZJ_HUODONG'
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("changeFestStatus")
	public void changeFestStatus(
			@RequestParam(required = true) String activityId,
			@RequestParam(required = true) String type,
			@RequestParam(required = true) Integer useNum, String remophone,
			String region, HttpServletRequest request,
			HttpServletResponse response) {

		try {
			// 活动表示
			if (!type.equals(AesConstant.HUODONG)) {
				jsonResult(0, "153", "扫描活动非法请求修改活动状态", "", response);
				return;
			}
			ActDetailAndFestAndUserVO vo = czjactivityService
					.getActDeAndFestUser(activityId);
			if (null == vo) {
				jsonResult(0, "171", "用户订单信息异常", "", response);
				return;
			}
			//活动是否过期
			if(null!=vo.getEndTime()){
				if(new Date().getTime()>vo.getEndTime().getTime()){
					jsonResult(0, "177", "活动已经结束", "", response);
				}
			}
			
			
			//已使用数量
			Integer  idenNum=czjromotionService.getSumNumByActId(activityId);
			
			if(null==idenNum){
				idenNum=0;
			}
			// 本次可使用数量
			Integer num = vo.getNun() - idenNum.intValue(); 
			if (useNum > num) {
				jsonResult(0, "172", "本次使用数量大于可使用数量", num, response);
				return;
			}
			Czjromotion czjromotion = new Czjromotion();
			czjromotion.setRomotionId(UUIDUtils.getUUID());
			czjromotion.setActivityId(vo.getActivityId());
			czjromotion.setActivityNum(vo.getActivityNum());
			czjromotion.setUserinfoId(vo.getUserinfoId());
			czjromotion.setNum(useNum);
			czjromotion.setPrice(vo.getBuyingPrice());
			czjromotion.setFestId(vo.getFestivalActId());
			czjromotion.setFestName(vo.getFestName());
			czjromotion.setTelephone(vo.getTelephone());
			czjromotion.setNickname(vo.getNickname());
			czjromotion.setRemophone(remophone);
			czjromotion.setRegion(region);
			czjromotion.setCreatetime(new Date());
			// 修改活动状态

			if ((idenNum.intValue()+useNum==vo.getNun())) {

				Czjactivity czjactivity = new Czjactivity();
				czjactivity.setActivityId(activityId);
				czjactivity.setStatus(OrderStatus.USE.getIndex());
				czjactivityService.updateAct(czjactivity);

			}
			czjromotionService.insert(czjromotion);
			jsonResult(1, "", "", "", response);

		} catch (Exception e) {
			e.printStackTrace();
			log.error("err", e);
			jsonResult(0, "152", "修改活动订单状态失败", "", response);
		}
	}

	/**
	 * 
	 * 方法名：list 后台显示假日活动订单 创建人：RUI 时间：2017年6月6日-上午9:27:35
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param telephone
	 * @param activityNum
	 * @param beginTime
	 * @param endTime
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("list")
	public String list(Integer pageNo, Integer pageSize, String telephone,
			String activityNum, String beginTime, String endTime,String festivalActId,
			String status, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		modelMap.addAttribute("failed",request.getParameter("failed"));
		modelMap.addAttribute("success",request.getParameter("success"));

		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(telephone)) {
			map.put("telephone", telephone);
			modelMap.addAttribute("telephone", telephone);
		}
		if (StringUtils.isNotBlank(activityNum)) {
			map.put("activityNum", activityNum);
			modelMap.addAttribute("activityNum", activityNum);
		}
		if (StringUtils.isNotBlank(status)) {
			map.put("status", status);
			modelMap.addAttribute("status", status);
		}
		if (StringUtils.isNotBlank(festivalActId)) {
			map.put("festivalActId", festivalActId);
			modelMap.addAttribute("festivalActId", festivalActId);
		}
		if (StringUtils.isNotBlank(beginTime)) {
			map.put("beginTime", beginTime);
			map.put("createTime", 11);
			if (StringUtils.isBlank(endTime)) {
				map.put("endTime",
						LocalDateTime.getDate(new Date(), "yyyy-MM-dd HH:mm"));
				modelMap.addAttribute("endTime",
						LocalDateTime.getDate(new Date(), "yyyy-MM-dd HH:mm"));
			} else {
				map.put("endTime", endTime);
				modelMap.addAttribute("endTime", endTime);
			}
			modelMap.addAttribute("beginTime", beginTime);

		}
		try {

			int pay1 = czjactivityService.getPay1();// 未完成
			int pay2 = czjactivityService.getPay2();// 已完成
			modelMap.addAttribute("pay1", pay1);

			modelMap.addAttribute("pay2", pay2);
			if (null == pageNo)
				pageNo = PageInfo.DEFAULT_PAGENO;
			if (null == pageSize)
				pageSize = PageInfo.DEFAULT_PAGESIZE;
			
			//查询所有活动
			
			List<Map<String,Object>> fests=czjfestivalactService.getAllFest();
			modelMap.addAttribute("fests", fests);
			Pagination pagination = czjactivityService.listCzjactivity(map,
					pageNo, pageSize);
			modelMap.addAttribute("pagination", pagination);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("err", e);

		}

		return "activity/list";
	}

	/**
	 * 
	 * 方法名：deleteAct 后台假删除 创建人：RUI 时间：2017年6月6日-上午9:44:54
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param activityId
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("deleteAct")
	public String deleteAct(Integer pageNo, Integer pageSize,
			String activityId, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {

		try {
			Czjactivity czjactivity = new Czjactivity();
			czjactivity.setActivityId(activityId);
			czjactivity.setDel(0);

			czjactivityService.updateAct(czjactivity);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/activity/list?pageNo=" + pageNo;
	}

	@RequestMapping("detail")
	public String detail(Integer pageNo, Integer pageSize, String activityId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("activityId", activityId);
			ActDetailAndFest czjactivity = czjactivityService
					.getActDetailAndFest(map);
			//优惠券
			czjusecouponService.setCouponsByOrderCode(czjactivity.getActivityNum(),czjactivity.getCouponsId(),modelMap);
			modelMap.put("czjactivity", czjactivity);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "activity/detail";
	}
	//活动订单退款
	@RequestMapping("refund.do")
	public String refund(String orderno, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response,
						 ModelMap modelMap) throws UnsupportedEncodingException {

		try {
			Xyuser user = (Xyuser) httpSession.getAttribute("user");
			if (null == user) {

				modelMap.addAttribute("error", "用户为空");
				return "admin/nopermissions";
			} else {


				Map<String, Object> map = czjactivityService.getOrderedByNo(orderno);
				if(map==null) {
					return "redirect:/activity/list?failed="+ URLEncoder.encode("活动订单退款失败！订单号不存在","UTF-8");

				}
				Czjactivity activity = czjactivityService.queryById((String) map.get("activityId"));

				if(OrderStatus.UNUSE.getIndex()!=activity.getStatus()){
					return "redirect:/activity/list?failed="+ URLEncoder.encode("活动订单退款失败！只有在未使用的情况下才可以退款。","UTF-8");
				}

				Czjrefund czjrefund = czjrefundService.queryByOrderCode(activity.getActivityNum());
				if(czjrefund==null){
					czjrefund = new Czjrefund();
					czjrefund.setRefundId(UUIDUtils.getUUID());
					czjrefund.setBusinessId("");
					czjrefund.setUserinfoId(activity.getUserinfoId());
					czjrefund.setRefundAmount(activity.getTotalAmount());
					czjrefund.setOrderCode(activity.getActivityNum());
					czjrefund.setDelFlag(0);
					czjrefund.setCreatetime(new Date());
					czjrefund.setRefundStatus(RefundStatus.RUNNING.getIndex());
					czjrefundService.insert(czjrefund);
				}

				String obj1 = czjrefundService.refundSu(activity.getTotalAmount(), activity.getActivityNum());
				if (obj1 != null) return "redirect:/activity/list?failed="+ URLEncoder.encode(obj1,"UTF-8");
				czjactivityService.updateOrderStatus(activity.getActivityNum(),OrderStatus.REFUNDED.getIndex());
				return "redirect:/activity/list?success="+ URLEncoder.encode("活动订单退款成功。","UTF-8");


			}


	} catch (Exception e) {
			e.printStackTrace();
			log.error("#Error:",e);
			return "redirect:/activity/list?failed="+URLEncoder.encode("退款操作失败！","UTF-8");
		}

	}


	@Autowired
	private CzjactivityService czjactivityService;
	@Autowired
	private CzjactdetailService czjactdetailService;
	@Autowired
	private CzjawarduseService czjawarduseService;
	@Autowired
	private CzjromotionService czjromotionService;
	@Autowired
	private CzjfestivalactService czjfestivalactService;
	@Autowired
	private CzjusecouponService czjusecouponService;
	@Autowired
	private CzjawardstockService czjawardstockService;
	@Autowired
	private CzjrefundService czjrefundService;


}